/**	
	*	
	*	Identify tool

	*				
	*	thiet lap che do identify tren ban do		
	*		
	*	History:	
	*			
	
	*			DATE									AUTHOR						DESCRIPTION		
	*		--------------------------------------------------------------------------------------		
	*		25-12-2012			Tuannh							Create	new	
	*
*/


/************ iqxTree *******************/
treeviewPL =
{
	numberItem: 0,
	listFeatureHistory : null,
	map : null,
	leftPanel : null,
	rightPanel : null,
	vectorGraphics : null,
	
	/* bo lua chon doi tuong duoc identify tren ban do */ 
	clearSelectionIdentify: function()
	{
        // xoa nhung doi tuong dc chon - tro ve trang thai ban dau
        if(treeviewPL.listFeatureHistory != null)
        {
        	for(var i=0;i<treeviewPL.listFeatureHistory.length;i++)
        	{
            	var obj = treeviewPL.listFeatureHistory[i];
            	var idxLayer = obj[0];
            	var fidFeature = obj[1];
                layer = treeviewPL.map.layers[idxLayer];
                featureCurrentAction = layer.getFeatureByFid(fidFeature);
                layer.drawFeature(featureCurrentAction, 'default');
                // an lop ban do WFS
                MapAction.HideWFS(idxLayer);
        	}
        	vectorGraphics.removeAllFeatures();
        }
	},
	
	// xac dinh the "li" la layer hoac feature - neu co thi tra ve doi tuong
	findLayerFeatureFromLayerIndex : function(idLayerFeature, layerindex, fid, typeobj) {
		var bObj = null;
        // luon luon select phan tu dau tien
        $('#jqxTree_Identify').jqxTree('selectItem', $("#jqxTree_Identify").find('li:first')[0]);
        var selectedItem = $("#jqxTree_Identify").jqxTree('selectedItem');
        var nextItem = selectedItem.nextItem; 
        if (nextItem == null) {
            bObj = null;
        }
        else {
            while (nextItem != null) {
                var element = nextItem.element;
                if (typeobj.toLowerCase() == "layer") {
                    if (idLayerFeature != null) {
                        if (element.id.toLowerCase() == idLayerFeature.toLowerCase()) {
                            bObj = element;
                            break;
                        }
                    }
                    else {
                        objLI = element;
                        var objLITypeObj = "";
                        var objLILayerIndex = "";
                        for (var j = 0; j < objLI.attributes.length; j++) {
                            if (objLI.attributes[j].name.toLowerCase() == "typeobj") {
                                objLITypeObj = objLI.attributes[j].value;
                            }
                            if (objLI.attributes[j].name.toLowerCase() == "layerindex") {
                                objLILayerIndex = objLI.attributes[j].value;
                            }
                        }
                        if (objLITypeObj == "") objLITypeObj = objLI.typeObj;
                        if (objLILayerIndex == "") objLILayerIndex = objLI.layerIndex;

                        // neu tim dc the 'li' ung voi layerindex thi ko tao moi
                        if ((objLITypeObj.toLowerCase() == typeobj.toLowerCase()) && (objLILayerIndex == layerindex)) {
                            bObj = objLI;
                            break;
                        }
                    }
                }
                else {
                    if (idLayerFeature != null) {
                        if (element.id == idLayerFeature) {
                            bObj = element;
                            break;
                        }
                    }
                    else {
                        objLI = element;
                        var objLITypeObj = "";
                        var objLILayerIndex = "";
                        var objLIFID = "";
                        for (j = 0; j < objLI.attributes.length; j++) {
                            if (objLI.attributes[j].name.toLowerCase() == "typeobj") {
                                objLITypeObj = objLI.attributes[j].value;
                            }
                            if (objLI.attributes[j].name.toLowerCase() == "layerindex") {
                                objLILayerIndex = objLI.attributes[j].value;
                            }
                            if (objLI.attributes[j].name.toLowerCase() == "fid") {
                                objLIFID = objLI.attributes[j].value;
                            }
                        }
                        if (objLITypeObj == "") objLITypeObj = objLI.typeObj;
                        if (objLILayerIndex == "") objLILayerIndex = objLI.layerIndex;

                        // neu tim dc the 'li' ung voi layerindex thi ko tao moi
                        if ((objLITypeObj.toLowerCase() == typeobj.toLowerCase()) && (objLILayerIndex == layerindex)) {
                            if (objLIFID == fid)
                            {
                            	bObj = objLI;                            	
                            	break;
                            }
                        }
                    }
                }
                nextItem = nextItem.nextItem; 
            }
        }
        return bObj;
	},
	
	// xac dinh the "li" la layer hoac feature - neu co thi tra ve 1
	isLayerFeatureFromLayerIndex : function(idLayerFeature, layerindex, fid, typeobj) {
		var bFind = 0;
        // luon luon select phan tu dau tien
        $('#jqxTree_Identify').jqxTree('selectItem', $("#jqxTree_Identify").find('li:first')[0]);
        var selectedItem = $("#jqxTree_Identify").jqxTree('selectedItem');
        var nextItem = selectedItem.nextItem; 
        if (nextItem == null) {
            bFind = 0;
        }
        else {
            while (nextItem != null) {
                var element = nextItem.element;
                // tim the LI ung voi layerIndex
                var objLI = element;
                var objLITypeObj = "";
                var objLILayerIndex = "";
                for (var j = 0; j < objLI.attributes.length; j++) {
                    if (objLI.attributes[j].name.toLowerCase() == "typeobj") {
                        objLITypeObj = objLI.attributes[j].value;
                    }
                    if (objLI.attributes[j].name.toLowerCase() == "layerindex") {
                        objLILayerIndex = objLI.attributes[j].value;
                    }
                }
                if (objLITypeObj == "") objLITypeObj = objLI.typeObj;
                if (objLILayerIndex == "") objLILayerIndex = objLI.layerIndex;

                // neu tim dc the 'li' ung voi layerindex thi ko tao moi
                if ((objLITypeObj.toLowerCase() == typeobj.toLowerCase()) && (objLILayerIndex == layerindex)) {
                    if (typeobj.toLowerCase() == "layer") bFind = 1;
                    else {
                        if (objLI.fid == fid) bFind = 1;
                    }
                    break;
                }
                nextItem = nextItem.nextItem; 
            }
        }

        return bFind;
	},
	
	// them node vao treeview
	_addTree : function(type, layerindex, fid, displayName) {
        if (type == "layer") {
            var bFind = this.isLayerFeatureFromLayerIndex(null, layerindex, "", "layer");
            if (bFind == 1) return;
            $('#jqxTree_Identify').jqxTree('selectItem', $("#jqxTree_Identify").find('li:first')[0]);
            var selectedItem = $('#jqxTree_Identify').jqxTree('selectedItem');
            if (selectedItem != null) {
                // adds an item with label: 'item' as a child of the selected item. The last parameter determines whether to refresh the Tree or not.
                // If you want to use the 'addTo' method in a loop, set the last parameter to false and call the 'render' method after the loop.
                $('#jqxTree_Identify').jqxTree('addTo', 
                		{ label: displayName, typeObj: 'layer', layerIndex: layerindex, id: "li_" + layerindex + "aaa" }, 
                		selectedItem.element, false);
                var element = this.findLayerFeatureFromLayerIndex("li_" + layerindex + "aaa", layerindex, "", "layer");
                if (element != null) {
                    element.setAttribute("item-expanded", true);
                    element.setAttribute("layerIndex", layerindex);
                    element.setAttribute("typeObj", "layer");
                }
                // cap nhat lai cho treeview
                $('#jqxTree_Identify').jqxTree('render');
            }
            else {
                $('#jqxTree_Identify').jqxTree('addTo', { label: 'Item' }, false);
                // cap nhat lai cho treeview
                $('#jqxTree_Identify').jqxTree('render');
            }
        }
        else {
            var element = this.findLayerFeatureFromLayerIndex(null, layerindex, "", "layer");
            if (element == null) return;
            var objFeature = this.findLayerFeatureFromLayerIndex(null, layerindex, fid, "feature");
            if (objFeature != null) return;
            // tao moi nut
            $('#jqxTree_Identify').jqxTree('addTo', 
            		{ label: displayName, typeObj: 'feature', layerIndex: layerindex, id: "li_fea" + layerindex + "_" + fid }, 
            		element, false);
            objFeature = this.findLayerFeatureFromLayerIndex("li_fea" + layerindex + "_" + fid, layerindex, "", "feature");
            if (objFeature != null) {
                objFeature.setAttribute("item-expanded", true);
                objFeature.setAttribute("layerIndex", layerindex);
                objFeature.setAttribute("typeObj", "feature");
                objFeature.setAttribute("fid", fid);
            }
            // cap nhat lai cho treeview
            this.numberItem=this.numberItem+1;
            $('#jqxTree_Identify').jqxTree('render');
        }
        $('#jqxTree_Identify').jqxTree('selectItem', $("#jqxTree_Identify").find('li:first')[0]);
	},
	
	// tao treeview
	createTree : function() {
		var theme = "";
        // tao tree
        $('#jqxTree_Identify').jqxTree({ theme: theme, height: '100%', width: '100%' });
        $("#div_Map_divIdentify").jqxSplitter({ theme: theme, panels: [{ size: 150}] });

        $('#div_Map_divIdentify').bind('select', function (event) {
        	if(event.args==undefined || event.args == null) return;
            var typeObj = "";
            var layerIndex = -1;
            var fid = "";
            for (var i = 0; i < event.args.element.attributes.length; i++) {
                if (event.args.element.attributes[i].name.toLowerCase() == "typeobj") {
                	typeObj = event.args.element.attributes[i].value;
                }
                if (event.args.element.attributes[i].name.toLowerCase() == "layerindex") {
                	layerIndex =  event.args.element.attributes[i].value;
                }
                if (event.args.element.attributes[i].name.toLowerCase() == "fid") {
                    fid = event.args.element.attributes[i].value;
                }                
            }
            // nut goc
            treeviewPL.clearSelectionIdentify();   
            if(layerIndex=="-1") return;
            var layer = null;
            var featureCurrentAction = null;         
            // neu la layer
            if(typeObj=="layer") return;
            // neu la feature
            layer = treeviewPL.map.layers[layerIndex];
            var sLayerID = layer.protocol.featureType;
            switch(sLayerID.toLowerCase())
            {
	            case "giss_b_diaphanhuyen":
	            	for(var i=0;i<arrFeatureDistrict.length;i++)
	            	{
	            		if(arrFeatureDistrict[i].fid==fid)
	            		{
	            			featureCurrentAction=arrFeatureDistrict[i];
	            			break;
	            		}
	            	}
	            	vectorGraphics.addFeatures(featureCurrentAction);
	            	vectorGraphics.drawFeature(featureCurrentAction, 'select');
	            	break;
	            case "giss_b_diaphanxa":
	            	for(var i=0;i<arrFeatureCommune.length;i++)
	            	{
	            		if(arrFeatureCommune[i].fid==fid)
	            		{
	            			featureCurrentAction=arrFeatureCommune[i];
	            			break;
	            		}
	            	}
	            	vectorGraphics.addFeatures(featureCurrentAction);
	            	vectorGraphics.drawFeature(featureCurrentAction, 'select');
	            	break;
	            default:
	                featureCurrentAction = layer.getFeatureByFid(fid);
	            	// hien lop ban do WFS
	            	layer.setVisibility(true);
	            	layer.drawFeature(featureCurrentAction, 'select');
	            	break;
            }
            // tao table chua thong tin
            base.removeChildDiv(treeviewPL.rightPanel);
        	var objTable = document.createElement("table");
        	objTable.id = "tbl_Map_AddFeature_Attribute";
        	objTable.style.width = "100%";
        	objTable.style.margin = "5px";
        	objTable.style.padding = "5px";
            var arrField_Alias_Current = new Array();
			for (i = 0; i < arrField_Alias.length; i++) {
				if (base.trim(arrField_Alias[i].LayerName.toLowerCase()) == base.trim(sLayerID.toLowerCase())) {
					arrField_Alias_Current[arrField_Alias_Current.length] = arrField_Alias[i];
				}
			}
			var width_Column = 100;
			for ( var i = 0; i < arrField_Alias_Current.length; i++) {
				if(arrField_Alias_Current[i].Name == "fid") continue;
				var objTR_Alias = document.createElement("tr");
				var objTD_Title_Alias = document.createElement("td");
				objTD_Title_Alias.innerHTML = arrField_Alias_Current[i].Alias;
				var objTDTextAlias = document.createElement("td");
				
				if (arrField_Alias_Current[i].Type == "date") {
					var inputTextAlias = document.createElement("input");
					inputTextAlias.type = "text";
					inputTextAlias.style.width = width_Column + "px";
					inputTextAlias.id = sNameSpace + "date_Map_AddFeature_Attribute_" + arrField_Alias_Current[i].Name;
					$date = $(inputTextAlias);
					if (featureCurrentAction != null) {
						var objValue = null;
						if (featureCurrentAction.feature) {
							objValue = featureCurrentAction.feature.attributes[arrField_Alias_Current[i].Name];
						} else {
							objValue = featureCurrentAction.attributes[arrField_Alias_Current[i].Name];
						}
						if (objValue != undefined) {
							var currentTime = objValue;
							var splitDate = currentTime.split('-');
							var year = parseInt(splitDate[0]);
							var month = parseInt(splitDate[1]);
							var day = parseInt(splitDate[2]);
							currentTime = new Date(year, month, day);
							$date.val(currentTime.getDate() + "/" + (currentTime.getMonth()) + "/" + currentTime.getFullYear());
						}
						else
						{
							var currentTime = new Date();
							var year = currentTime.getFullYear();
							var month = currentTime.getMonth() + 1;
							var day = currentTime.getDate();
							if(month<10) month = "0" + month;
							if(day<10) day = "0" + day;
							var date = year + "-" + month + "-" + day;
							featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = date;
							$date.val(day + "/" + month +"/" + year);
						}
					} else {
						var currentTime = new Date();
						$date.val(currentTime.getDate() + "/" + (currentTime.getMonth() + 1) + "/" + currentTime.getFullYear());
					}
					inputTextAlias.attribute = arrField_Alias_Current[i].Name;
					$date.attr('readonly', true);
					objTDTextAlias.appendChild(inputTextAlias);
				} 
				else if (arrField_Alias_Current[i].Type == "img")
				{
					arrField_Alias_Current[i].IsShow = false;
				}
				else if (arrField_Alias_Current[i].IsCategory) {
					if (featureCurrentAction != null) {
						var objValue = null;
						objValue = featureCurrentAction.attributes[arrField_Alias_Current[i].Name];
						if(objValue == undefined) 
						{
							var inputTextAlias = document.createElement("input"); 
							inputTextAlias.type = "text";
							inputTextAlias.style.width = width_Column + "px";
							inputTextAlias.id = sNameSpace + "txt_Map_AddFeature_Attribute_" + arrField_Alias_Current[i].Name;
							$(inputTextAlias).val("<none>");
							objTDTextAlias.appendChild(inputTextAlias);
						}
						else
						{
							objValue = base.trim(objValue.replace(/(\r\n|\n|\r)/gm, ""));
							var $divMapData = $(document.createElement('div'));
							$divMapData.attr("Attr_Name", arrField_Alias_Current[i].Name);
							$divMapData.attr("Attr_Val", objValue);
							var sFileJSP = "identify/getDataFromCategory.jsp";
							arrTDAttribute[arrField_Alias_Current[i].Name] = objTDTextAlias;
							var sTableName = arrField_Alias_Current[i].TableName;
							$divMapData.load(sPortletJSP + sFileJSP + "?attr=" + arrField_Alias_Current[i].FieldValue 
									+ "&val=" + objValue + "&tbl=" + sTableName, function(data) {
								var inputTextAlias = document.createElement("input"); 
								inputTextAlias.type = "text";
								inputTextAlias.style.width = width_Column + "px";
								inputTextAlias.id = sNameSpace + "txt_Map_AddFeature_Attribute_" + $(this).attr("Attr_Name");
								data = base.trim(data.replace(/(\r\n|\n|\r)/gm, ""));
								if(data == '') $(inputTextAlias).val($(this).attr("Attr_Val"));
								else $(inputTextAlias).val(data);
								arrTDAttribute[$(this).attr("Attr_Name")].appendChild(inputTextAlias);
							});
						}
					}
				} else {
					var inputTextAlias = document.createElement("input");
					if (arrField_Alias_Current[i].Type.toLowerCase() == "bigtext") inputTextAlias = document.createElement("textarea");			
					else inputTextAlias.type = "text";
					inputTextAlias.style.width = width_Column + "px";
					inputTextAlias.id = sNameSpace + "txt_Map_AddFeature_Attribute_" + arrField_Alias_Current[i].Name;

					switch (arrField_Alias_Current[i].Name.toLowerCase()) {
					case "madiemdau":
					case "madiemcuoi":
						var maDiemDauCuoi = "";
						if (featureCurrentAction.feature) {
							maDiemDauCuoi = featureCurrentAction.feature.attributes[arrField_Alias_Current[i].Name];
						} else {
							maDiemDauCuoi = featureCurrentAction.attributes[arrField_Alias_Current[i].Name];
						}
						inputTextAlias.value = maDiemDauCuoi;
						break;
					case "quanhuyen":
						if (vectorDistricts != null) {
							var indexLayer = LayerTool.getIndexLayer();
							var bounds_District = featureCurrentAction.geometry.bounds;
							if (vectorArray[indexLayer - numBaseLayer].Geometry_Type == Geometries.Point) {
								var tolerance = 1;
								bounds_District.left -= tolerance;
								bounds_District.right += tolerance;
								bounds_District.top += tolerance;
								bounds_District.bottom -= tolerance;
							}
							var ii = 0;
							for (ii = 0; ii < arrFeatureDistrict.length; ii++) {
								var featureDistrict = arrFeatureDistrict[ii];
								var b = featureDistrict.geometry.bounds;
								if (bounds_District.intersectsBounds(b)) {
									inputTextAlias.value = featureDistrict.attributes["name_en"];
									if (featureCurrentAction.feature) {
										featureCurrentAction.feature.attributes[arrField_Alias_Current[i].Name] = inputTextAlias.value;
									} else {
										featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = inputTextAlias.value;
									}
									break;
								}
							}
						}
						break;
					case "phuongxa":
						if (vectorCommune != null) {
							var indexLayer = LayerTool.getIndexLayer();
							var bounds_Commune = featureCurrentAction.geometry.bounds;
							if (vectorArray[indexLayer - numBaseLayer].Geometry_Type == Geometries.Point) {
								var tolerance = 1;
								bounds_Commune.left -= tolerance;
								bounds_Commune.right += tolerance;
								bounds_Commune.top += tolerance;
								bounds_Commune.bottom -= tolerance;
							}
							var ii = 0;
							for (ii = 0; ii < arrFeatureCommune.length; ii++) {
								var featureDistrict = arrFeatureCommune[ii];
								var b = featureDistrict.geometry.bounds;
								if (bounds_Commune.intersectsBounds(b)) {
									inputTextAlias.value = featureDistrict.attributes["name_en"];
									if (featureCurrentAction.feature) {
										featureCurrentAction.feature.attributes[arrField_Alias_Current[i].Name] = inputTextAlias.value;
									} else {
										featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = inputTextAlias.value;
									}
									break;
								}
							}
						}
						break;
					default:
						if (featureCurrentAction != null) {
							var objValue = null;
							if (featureCurrentAction.feature) {
								objValue = featureCurrentAction.feature.attributes[arrField_Alias_Current[i].Name];
							} else {
								objValue = featureCurrentAction.attributes[arrField_Alias_Current[i].Name];
							}
							if (objValue != undefined)
								inputTextAlias.value = objValue;
						}
						break;
					}
					inputTextAlias.attribute = arrField_Alias_Current[i].Name;
					$(inputTextAlias).attr('readonly', true);
					inputTextAlias.style.fontSize = "12px";
					if (arrField_Alias_Current[i].Type == "int") {
						inputTextAlias.IsDecimal = 0;
						inputTextAlias.onkeydown = txtKeyDown;
					}
					if (arrField_Alias_Current[i].Type == "decimal") {
						inputTextAlias.IsDecimal = 1;
						inputTextAlias.onkeydown = txtKeyDown;
					}
					inputTextAlias.readonly = true;
					objTDTextAlias.appendChild(inputTextAlias);
				}
				objTR_Alias.appendChild(objTD_Title_Alias);
				objTR_Alias.appendChild(objTDTextAlias);
				objTable.appendChild(objTR_Alias);
				if (!arrField_Alias_Current[i].IsShow || arrField_Alias_Current[i].IsShow==null || arrField_Alias_Current[i].IsShow==undefined)
				{
					objTR_Alias.style.display = "none";
				}			
			}
			
        	treeviewPL.rightPanel.appendChild(objTable);	
			
            if(treeviewPL.listFeatureHistory == null) treeviewPL.listFeatureHistory = new Array();
            var objNewFeature = [];
            objNewFeature[0]=layerIndex;
            objNewFeature[1]=fid;
            treeviewPL.listFeatureHistory[treeviewPL.listFeatureHistory.length] = objNewFeature;
        });
	},
	
	/* bo tat ca doi tuong identify duoc chon tren ban do */
	removeAll: function()
	{
		this.numberItem=0;
		// xoa nut
        $('#jqxTree_Identify').jqxTree('selectItem', $("#jqxTree_Identify").find('li:first')[0]);
		var selectedItem = $('#jqxTree_Identify').jqxTree('selectedItem');
		selectedItem = selectedItem.nextItem;
        while(selectedItem != null) {
            // removes the selected item. The last parameter determines whether to refresh the Tree or not.
            // If you want to use the 'removeItem' method in a loop, 
        	// set the last parameter to false and call the 'render' method after the loop.
            $('#jqxTree_Identify').jqxTree('removeItem', selectedItem.element, false);
            selectedItem = selectedItem.nextItem;
        }
        // cap nhat lai cho treeview
        $('#jqxTree_Identify').jqxTree('render');

        treeviewPL.clearSelectionIdentify();
	}
};


//load thong tin thuo tin cua ban do quy hoach - zoomto toi lop ban do quy hoach
var timeoutGetBDQH = null;
var iNumLoadQH = 0; // neu > 10 thi se enableMainPage va clear timeout - de phong truong hop ko ca ban do QH 
function loadQuyHoach() {
	disableMainPage();
	$("#divDisableMap_Loader").show();    
	if(trvBandoQuyHoach.layerQHChung == null) return;
	if(trvBandoQuyHoach.layerQHChitiet == null) return;
	if (trvBandoQuyHoach.layerQHChung.features.length == 0) {
		var functionObj = "loadQuyHoach();";
		timeoutGetBDQH = setTimeout(functionObj, 500);
		iNumLoadQH++;
		if(iNumLoadQH > 10)
		{
			enableMainPage();
			$("#divDisableMap_Loader").hide();
			clearTimeout(timeoutGetBDQH);
		}
	} else {
		var i = 0;
		var sMaBDQH = trvBandoQuyHoach.maBDQH;
		/** fill data - phong toi ban do quy hoach chung ***/
 		var arrFeaturQHChung = trvBandoQuyHoach.layerQHChung.getFeaturesByAttribute(trvBandoQuyHoach.assetQHChung.MaVungQHChungField, sMaBDQH);
 		var feature = featureCurrentAction = arrFeaturQHChung[0];
 		trvBandoQuyHoach.assetQHChung.AttrInfoQH = [];
 		if(feature != undefined)
		{
	 		for (i = 0; i < trvBandoQuyHoach.assetQHChung.AliasName.length; i++){
	 			var sControlID = trvBandoQuyHoach.assetQHChung.AliasName[i].controlID;
	 			var objValue = feature.attributes[trvBandoQuyHoach.assetQHChung.AliasName[i].Name];
	 			if(trvBandoQuyHoach.assetQHChung.AliasName[i].Type == 'file') 
 				{
	 				if(objValue != undefined) 
	 					trvBandoQuyHoach.assetQHChung.AttrInfoQH[trvBandoQuyHoach.assetQHChung.AliasName[i].Name] = objValue;
	 				continue;
 				}
	 			if(trvBandoQuyHoach.assetQHChung.AliasName[i].Type == 'date' && objValue != undefined) 
 				{
	 				// format: yyyy-mm-dd
	 				objValue = objValue.split('-');
	 				if(objValue.length == 3)
 					{
		 				// format: dd/mm/yyyy
		 				objValue = objValue[2] + '/' + objValue[1] + '/' + objValue[0];
		 				$('#' + sControlID).datepicker('setDate', objValue);
 					}
 				}
	 			else 
 				{
	 				if(objValue != undefined) $('#' + sControlID).val(objValue);
 				}
	 			if(objValue != undefined) trvBandoQuyHoach.assetQHChung.AttrInfoQH[trvBandoQuyHoach.assetQHChung.AliasName[i].Name] = objValue;
	 		}	 			
		}
 		$('#' + trvBandoQuyHoach.assetQHChung.fieldsetID + ' select').uniform();
		// phong to toi vung quy hoach chung
		var extent = feature.geometry.getBounds(); //trvBandoQuyHoach.layerQHChung.getDataExtent();
		if (extent != null) map.zoomToExtent(extent);
		/************************************/
		/** fill data ban do quy hoach chi tiet ***/
 		var arrFeaturQHChung = trvBandoQuyHoach.layerQHChitiet.getFeaturesByAttribute(
 				trvBandoQuyHoach.assetQHChitiet.MaVungQHChungField, sMaBDQH);
 		var feature = arrFeaturQHChung[0];
 		trvBandoQuyHoach.assetQHChitiet.AttrInfoQH = [];
 		if(feature != undefined)
 		{
	 		for (i = 0; i < trvBandoQuyHoach.assetQHChitiet.AliasName.length; i++){
	 			var sControlID = trvBandoQuyHoach.assetQHChitiet.AliasName[i].controlID;
	 			var objValue = feature.attributes[trvBandoQuyHoach.assetQHChitiet.AliasName[i].Name];
	 			if(trvBandoQuyHoach.assetQHChitiet.AliasName[i].Type == 'file') 
 				{
	 				if(objValue != undefined) trvBandoQuyHoach.assetQHChitiet.AttrInfoQH[trvBandoQuyHoach.assetQHChitiet.AliasName[i].Name] = objValue;
	 				continue;
 				}
	 			if(trvBandoQuyHoach.assetQHChitiet.AliasName[i].Type == 'date' && objValue != undefined)
 				{
	 				// format: yyyy-mm-dd
	 				objValue = objValue.split('-');
	 				if(objValue.length == 3)
 					{
		 				// format: dd/mm/yyyy
		 				objValue = objValue[2] + '/' + objValue[1] + '/' + objValue[0];
		 				$('#' + sControlID).datepicker('setDate', objValue);
 					}
 				}
	 			else 
 				{
	 				if(objValue != undefined) $('#' + sControlID).val(objValue);
 				}
	 			if(objValue != undefined) trvBandoQuyHoach.assetQHChitiet.AttrInfoQH[trvBandoQuyHoach.assetQHChitiet.AliasName[i].Name] = objValue;
	 		}	 			
		}
 		$('#' + trvBandoQuyHoach.assetQHChitiet.fieldsetID + ' select').uniform();
		/************************************/
		$("#ui-datepicker-div").hide();
		enableMainPage();
		$("#divDisableMap_Loader").hide();
		clearTimeout(timeoutGetBDQH);

	    // load quy hoach chi tiet vao combobox
	    assetQHCHITIET.loadVungQHChiTietToCombobox(sMaBDQH);
	}
};
/*********** treeview trong jQuery *********/
var treeView = function()
{
	this.aCurrent = null;
	this.itemIndex = 0; // chi so cac tai san dung trong tu dieu khien
	this.MaBandoquyhoach = "";	
	this.soluongvungQH = 0;
	
	this.addNodeBandoquyhoach = function(idParentNode, textNode, maBDQH, tabValue)
	{
		if(textNode == '') return;
		var ulObj = $("#" + idParentNode);
		var li = document.createElement("li");
		var aObj = document.createElement("a");
		$(aObj).text(textNode);
		$(aObj).attr('href','#');
		$(aObj).attr('tab', tabValue);
		$(aObj).attr('maBDQH', maBDQH);
		$(aObj).mousedown(function() {			
			$(this).css('color','#ff0000');
			$(this).parent().find('img').remove();
			$(this).parent().siblings().each(function(){
				$(this).find('a').css('color','#000000');
				// xoa anh del - edit quy hoach
				$(this).find('img').remove();
			});
			

			// delete quy hoach
			var imgDel = document.createElement("img");
			imgDel.src = "/AnGiang-557-portlet/html/giamsatmoitruong/images/delete.png";
			imgDel.alt = imgDel.title = LANGUAGE['msg_delete_1'] + ' ' + textNode;
			$(imgDel).css('margin-left', '5px');
			$(imgDel).css('margin-top', '-1px');
			$(imgDel).css('cursor', 'pointer');
			$(imgDel).click(function() {
				assetQHCHUNG.delBDQH();
			});
			// edit quy hoach
			var imgEdit = document.createElement("img");
			imgEdit.src = "/AnGiang-557-portlet/html/giamsatmoitruong/images/edit.png";
			imgEdit.alt = imgEdit.title = LANGUAGE['msg_edit_1'] + ' ' + textNode;
			$(imgEdit).css('margin-left', '5px');
			$(imgEdit).css('margin-top', '-1px');
			$(imgEdit).css('cursor', 'pointer');
			var liParent = $(this).parent();
			//$(liParent).append(imgEdit);
			$(liParent).append(imgDel);
			
			
			
			var tabValue = $(this).attr('tab'); //items;
			items = tabValue.split('---');

			base.enabledAll(document.getElementById('div_Map_QHChung_Tabs'));
			assetQHCHUNG.enabledAll();
			assetQHCHUNG.STATUS_ASSET = STATUS_ASSET.UPDATE;
			assetQHCHITIET.STATUS_ASSET = STATUS_ASSET.UPDATE;
			
			var sMaBDQH = $(this).attr('maBDQH');
			var layerName = "";
			var objVectorLayer = null;
			var indexLayer = -1;
			var objLayerQHChung = null, objLayerQHChitiet = null;

			// thiet lap cookie cho vumg quy hoach
			Cookies.setCookie(QHCHUNG_COOKIE, sMaBDQH, 365);
			
			layerName = assetQHCHUNG.layerName;
			objVectorLayer = LayerTool.getVectorLayer(layerName);
	 		indexLayer = objVectorLayer.IndexLayer;
	 		objLayerQHChung = map.layers[indexLayer];
			//map.removeLayer(objLayerQHChung);
	 		/**** loc du lieu theo ma quy hoach chung *****/
			/*var vectorItem = vectorArray[indexLayer];
			var saveFeature = vectorItem.SaveObj;
			objLayerQHChung = new OpenLayers.Layer.Vector(vectorItem.Layer_Name, {
				projection : new OpenLayers.Projection(vectorItem.Projection),
				strategies : [ new OpenLayers.Strategy.BBOX(), saveFeature ],
				protocol : new OpenLayers.Protocol.WFS({
					version : vectorItem.Version, // "1.0.0
					url : vectorItem.URL,
					featureType : vectorItem.Feature_Type,
					featureNS : vectorItem.Feature_NS,
					geometryName : vectorItem.Geometry_Name
				})
				,styleMap : vectorItem.StyleMap
		        ,filter: new OpenLayers.Filter.Logical({
		        	type: OpenLayers.Filter.Logical.OR,
		        	filters: [
		    	          new OpenLayers.Filter.Comparison({
		    	        	  type: OpenLayers.Filter.Comparison.EQUAL_TO,
		                      property: assetQHCHUNG.MaVungQHChungField,
		                      value: sMaBDQH
		    	          })
			          ]	
		        })
			});
			objLayerQHChung.refresh({force:true});
		    map.addLayer(objLayerQHChung);
		    map.setLayerIndex(objLayerQHChung, indexLayer);
		    objLayerQHChung.redraw();*/

			/*********** filter data theop mapservice *********************/
			var indexLayerWMS = LayerTool.getIndexLayerFromName_Mapservice(vectorArray[indexLayer].LayerId);
			var layerOBJ = map.layers[indexLayerWMS];
			// fileter mapservice 
			var filter = assetQHCHUNG.MaVungQHChungField + " = '" + sMaBDQH + "'"; 
			layerOBJ.mergeNewParams({"CQL_FILTER": filter});
			layerOBJ.redraw();			
	 		/****************************************/
	 		assetQHCHUNG.MaQHChung = sMaBDQH;			
			
			/*** fill data cho ban do quy hoach chi tiet ***/	 
	 		layerName = assetQHCHITIET.layerName;
			objVectorLayer = LayerTool.getVectorLayer(layerName);
	 		indexLayer = objVectorLayer.IndexLayer;
	 		objLayerQHChitiet = map.layers[indexLayer];
			//map.removeLayer(objLayerQHChitiet);
	 		/**** loc du lieu theo ma quy hoach chi tiet *****/
			/*var vectorItem = vectorArray[indexLayer];
			var saveFeature = vectorItem.SaveObj;
			objLayerQHChitiet = new OpenLayers.Layer.Vector(vectorItem.Layer_Name, {
				projection : new OpenLayers.Projection(vectorItem.Projection),
				strategies : [ new OpenLayers.Strategy.BBOX(), saveFeature ],
				protocol : new OpenLayers.Protocol.WFS({
					version : vectorItem.Version, // "1.0.0
					url : vectorItem.URL,
					featureType : vectorItem.Feature_Type,
					featureNS : vectorItem.Feature_NS,
					geometryName : vectorItem.Geometry_Name
				})
				,styleMap : vectorItem.StyleMap
		        ,filter: new OpenLayers.Filter.Logical({
		        	type: OpenLayers.Filter.Logical.OR,
		        	filters: [
		    	          new OpenLayers.Filter.Comparison({
		    	        	  type: OpenLayers.Filter.Comparison.EQUAL_TO,
		                      property: assetQHCHUNG.MaVungQHChungField,
		                      value: sMaBDQH
		    	          })
			          ]	
		        })
			});
			objLayerQHChitiet.refresh({force:true});
		    map.addLayer(objLayerQHChitiet);
		    map.setLayerIndex(objLayerQHChitiet, indexLayer);
		    objLayerQHChitiet.redraw();*/

			/*********** filter data theop mapservice *********************/
			var indexLayerWMS = LayerTool.getIndexLayerFromName_Mapservice(vectorArray[indexLayer].LayerId);
			var layerOBJ = map.layers[indexLayerWMS];
			// fileter mapservice 
			var filter = assetQHCHUNG.MaVungQHChungField + " = '" + sMaBDQH + "'"; 
			layerOBJ.mergeNewParams({"CQL_FILTER": filter});
			layerOBJ.redraw();			
	 		/****************************************/
	 		assetQHCHUNG.MaQHChung = sMaBDQH;
	 		trvBandoQuyHoach.layerQHChung = objLayerQHChung;
	 		trvBandoQuyHoach.assetQHChung = assetQHCHUNG;
	 		trvBandoQuyHoach.layerQHChitiet = objLayerQHChitiet;
	 		trvBandoQuyHoach.assetQHChitiet = assetQHCHITIET;
	 		trvBandoQuyHoach.maBDQH = sMaBDQH;
	 		iNumLoadQH = 0;
	 		// thiet lap che do edit vung quy hoach
	 		actionCurrent = PortletTypeAction.Edit;
	 		// load thong itn vung quy hoach
		    loadQuyHoach();
	 		assetQHCHITIET.MaQHChiTiet = $("#txt_QHCHITIET_MaQHCHITIET").val();
	 		// an div import shp
	 		$("#div_QHCHUNG_SHP").hide();
	 		$("#div_QHCHITIET_SHP").hide(); 	
			// disabled ma quy hoach chung
			$(assetQHCHUNG.PKFIELDs[0]).attr('disabled', true);
	 		/****************************************/
		});
		/***** append element *****/
		$(li).append(aObj);
		$(ulObj).append(li);
		var maQHChung = Cookies.getCookie(QHCHUNG_COOKIE);
		//if(this.soluongvungQH == 1) $(aObj).mousedown();
		if(maQHChung == maBDQH) assetQHCHUNG.aObjQuyhoachActive = aObj; //$(aObj).mousedown();
	};
};
/******************************************/
var trvBandoQuyHoach = null;